package com.example.smartwaterapi.config;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * Sentinel限流配置
 */
@Configuration
public class SentinelConfig {

    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }

    /**
     * 初始化限流规则
     */
    @PostConstruct
    private void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();
        
        // 认证接口限流规则
        FlowRule authRule = new FlowRule();
        authRule.setResource("auth");
        // QPS限制为100
        authRule.setCount(100);
        authRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        authRule.setLimitApp("default");
        rules.add(authRule);
        
        // 用户接口限流规则
        FlowRule userRule = new FlowRule();
        userRule.setResource("user");
        // QPS限制为200
        userRule.setCount(200);
        userRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        userRule.setLimitApp("default");
        rules.add(userRule);
        
        // 水杯记录接口限流规则
        FlowRule waterRecordRule = new FlowRule();
        waterRecordRule.setResource("waterRecord");
        // QPS限制为300
        waterRecordRule.setCount(300);
        waterRecordRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        waterRecordRule.setLimitApp("default");
        rules.add(waterRecordRule);
        
        // 全局接口限流
        FlowRule globalRule = new FlowRule();
        globalRule.setResource("global");
        // QPS限制为500
        globalRule.setCount(500);
        globalRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        globalRule.setLimitApp("default");
        rules.add(globalRule);
        
        // 加载限流规则
        FlowRuleManager.loadRules(rules);
    }
} 